<template>
  <div class="user-stats-container">
    <el-card class="stats-card">
      <!-- 筛选条件 -->
      <div class="filter-container">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
        />
        <el-select
            v-model="statsType"
            placeholder="统计类型"
            style="width: 200px; margin-left: 10px"
        >
          <el-option
              v-for="item in statsTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="fetchUserStats" style="margin-left: 10px">
          <el-icon><Refresh /></el-icon>
          查询
        </el-button>
      </div>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-summary">
        <el-col :span="6">
          <el-statistic title="总用户数" :value="summary.totalUsers" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="新增用户" :value="summary.newUsers" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="活跃用户" :value="summary.activeUsers" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="留存率" :value="summary.retentionRate">
            <template #suffix>%</template>
          </el-statistic>
        </el-col>
      </el-row>

      <!-- 主图表 -->
<!--      <div class="chart-wrapper">
        <div ref="mainChart" style="height: 400px; width: 100%"></div>
      </div>-->

      <!-- 辅助图表 -->
<!--      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>用户类型分布</h4>
            <div ref="pieChart" style="height: 300px; width: 100%"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-wrapper">
            <h4>用户活跃时段</h4>
            <div ref="barChart" style="height: 300px; width: 100%"></div>
          </div>
        </el-col>
      </el-row>-->

      <!-- 数据表格 -->
      <div class="table-wrapper">
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            v-loading="loading"
        >
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="newUsers" label="新增用户" width="120" />
          <el-table-column prop="activeUsers" label="活跃用户" width="120" />
          <el-table-column prop="totalUsers" label="总用户数" width="120" />
          <el-table-column prop="retentionRate" label="留存率" width="120">
            <template #default="{ row }">
              {{ row.retentionRate }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Refresh } from '@element-plus/icons-vue'
//import axios from '@/utils/request'
import { ElMessage } from 'element-plus'

// 1. 定义图表引用
const mainChartRef = ref(null)
const pieChartRef = ref(null)
const barChartRef = ref(null)

// 2. 图表实例变量
let mainChart = null
let pieChart = null
let barChart = null

// 3. 筛选条件
const dateRange = ref([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
  new Date().toISOString().split('T')[0]
])
const statsType = ref('daily')
const statsTypeOptions = [
  { value: 'daily', label: '日统计' },
  { value: 'weekly', label: '周统计' },
  { value: 'monthly', label: '月统计' }
]

// 4. 统计数据
const summary = reactive({
  totalUsers: 0,
  newUsers: 0,
  activeUsers: 0,
  retentionRate: 0
})
const tableData = ref([])
const loading = ref(false)

// 5. 获取用户统计数据
const fetchUserStats = async () => {
  loading.value = true
  try {
    // 模拟API响应数据
    const mockData = {
      summary: {
        totalUsers: 1256,
        newUsers: 89,
        activeUsers: 567,
        retentionRate: 78.5
      },
      details: Array.from({ length: 30 }, (_, i) => ({
        date: new Date(Date.now() - (29 - i) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        newUsers: Math.floor(Math.random() * 20) + 5,
        activeUsers: Math.floor(Math.random() * 100) + 50,
        totalUsers: 1000 + i * 10,
        retentionRate: Math.floor(Math.random() * 20) + 70
      })),
      userTypeDistribution: [
        { value: 800, name: '普通用户' },
        { value: 300, name: 'VIP用户' },
        { value: 150, name: '企业用户' },
        { value: 6, name: '管理员' }
      ],
      activeHours: ['0-3', '3-6', '6-9', '9-12', '12-15', '15-18', '18-21', '21-24'],
      activeHoursData: [50, 80, 120, 200, 180, 150, 220, 100]
    }

    // 更新汇总数据
    Object.assign(summary, mockData.summary)
    tableData.value = mockData.details

    // 渲染图表
    nextTick(() => {
      renderCharts(mockData)
    })
  } catch (error) {
    ElMessage.error('获取统计数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 6. 渲染图表函数
const renderCharts = (data) => {
  renderMainChart(data)
  renderPieChart(data)
  renderBarChart(data)
}

const renderMainChart = (data) => {
  // 确保DOM已渲染
  if (!mainChartRef.value) return

  // 如果已有实例则销毁
  if (mainChart) {
    mainChart.dispose()
  }

  // 初始化图表
  mainChart = echarts.init(mainChartRef.value)

  const option = {
    title: {
      text: '用户增长趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['总用户数', '新增用户', '活跃用户'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.details.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总用户数',
        type: 'line',
        data: data.details.map(item => item.totalUsers),
        smooth: true,
        lineStyle: {
          width: 3
        }
      },
      {
        name: '新增用户',
        type: 'line',
        data: data.details.map(item => item.newUsers),
        smooth: true
      },
      {
        name: '活跃用户',
        type: 'line',
        data: data.details.map(item => item.activeUsers),
        smooth: true,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
            { offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
          ])
        }
      }
    ]
  }

  mainChart.setOption(option)
}

const renderPieChart = (data) => {
  if (!pieChartRef.value) return

  if (pieChart) {
    pieChart.dispose()
  }

  pieChart = echarts.init(pieChartRef.value)

  const option = {
    title: {
      text: '用户类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '用户类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.userTypeDistribution
      }
    ]
  }

  pieChart.setOption(option)
}

const renderBarChart = (data) => {
  if (!barChartRef.value) return

  if (barChart) {
    barChart.dispose()
  }

  barChart = echarts.init(barChartRef.value)

  const option = {
    title: {
      text: '用户活跃时段',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.activeHours
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '活跃用户',
        type: 'bar',
        data: data.activeHoursData,
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4']
            return colorList[params.dataIndex]
          }
        }
      }
    ]
  }

  barChart.setOption(option)
}

// 7. 窗口大小变化时重绘图表
const handleResize = () => {
  if (mainChart && typeof mainChart.resize === 'function') {
    mainChart.resize()
  }
  if (pieChart && typeof pieChart.resize === 'function') {
    pieChart.resize()
  }
  if (barChart && typeof barChart.resize === 'function') {
    barChart.resize()
  }
}

// 8. 组件生命周期
onMounted(() => {
  fetchUserStats()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  // 组件卸载时移除事件监听和销毁图表
  window.removeEventListener('resize', handleResize)
  mainChart && mainChart.dispose()
  pieChart && pieChart.dispose()
  barChart && barChart.dispose()
})
</script>

<style scoped>
.user-stats-container {
  padding: 20px;
}

.stats-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
}

.stats-summary {
  margin-bottom: 30px;
}

.chart-wrapper {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chart-wrapper h4 {
  margin: 0 0 15px 0;
  text-align: center;
  color: #666;
}

.table-wrapper {
  margin-top: 20px;
}

.el-statistic {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  height: 100%;
}
</style>